import React, { useState, useEffect, useRef } from "react";
import { Modal, Form, Input, Radio, Button, message, Tag } from "antd";
import { CloseOutlined } from "@ant-design/icons";
// css过渡
import { CSSTransition, TransitionGroup } from "react-transition-group";
import BlEditor from "@/components/BlEdit/BlMdEditor";
import Blpopver from "@/components/Blpopver";
import Blupload from "@/components/Blupload";
// 接口
import { queryAllCategory } from "@/api/cate.js";
import { queryAllTags } from "@/api/tag.js";
import { addArticle, getArticleInfoById } from "@/api/article.js";
// 样式
import dialogStyle from "./dialog.module.scss";
import popverStyle from "@/components/blpopver.module.scss";
import { modifyArticle } from "../../../api/article";
const requireRule = { required: true, message: "必填字段" };

export default function ArticleDialog(props) {
  const { isopen, setVisible, type, id } = props;
  const [loading, setLoading] = useState(false);
  const [titleImg, setTitleImg] = useState("");
  const [contentMd, setContentMd] = useState();
  const [form] = Form.useForm();
  const [tagList, setTagList] = useState([]);
  const [cateList, setCateList] = useState([]);
  const [tagsId, setTagsId] = useState([]);
  const [typeId, setTypeId] = useState({});
  useEffect(() => {
    if (isopen) {
      queryTags();
      queryCates();
      if (type === 1) {
        console.log(id, "id");
        queryArticleInfo();
      }
    }
  }, [isopen]);

  // 方法
  const queryArticleInfo = async () => {
    const res = await getArticleInfoById(id);
    console.log("--artilce-modify--", res);
    if (res.code === 200) {
      const {
        titleImg,
        title,
        summary,
        tagList,
        typeSort,
        status,
        isTop,
        isBanner,
        isRecommend,
        contentMd,
        composeType,
      } = res.data;
      form.setFieldsValue({
        title,
        summary,
        tagsId: tagList,
        typeId: { id: typeSort?typeSort.id:null, typeName: typeSort?typeSort.typeName:null },
        status,
        isTop,
        isBanner,
        isRecommend,
        composeType,
      });
      if (titleImg) {
        setTitleImg(titleImg);
      }
      setTagsId(tagList);
      setContentMd(contentMd);
      setTypeId({ id: typeSort?typeSort.id:null, typeName: typeSort?typeSort.typeName:null });
    } else {
      message.error(res.message);
    }
  };

  const queryTags = async () => {
    const res = await queryAllTags();
    console.log(res, "tags");
    setTagList(res.data);
  };
  const queryCates = async () => {
    const res = await queryAllCategory();
    console.log(res, "cates");
    setCateList(res.data.cateList);
  };
  // 对话框显示
  const handleOk = () => {
    console.log("取消");
    form.resetFields();
    setTagsId([]);
    setTypeId({});
    setContentMd("");
    setTitleImg("");
    setVisible(false, { type: "confirm" });
  };

  const handleCancel = () => {
    setTagsId([]);
    setTypeId({});
    setContentMd("");
    console.log("取消");
    setTitleImg("");
    form.resetFields();
    setVisible(false);
  };

  // 表单是否提交

  const handleFinishFail = (err) => {
    console.log("formerr", err);
  };
  const handleFinish = async (value) => {
    const cateId = typeId.id;
    const ids = tagsId.map((item) => item.id).join(",");
    const requestObj = { ...value, typeId: cateId, tagsId: ids };
    console.log("form", requestObj);
    if (type === 1) {
      try {
        setLoading(true);
        const res = await modifyArticle({ ...requestObj, id });
        setLoading(false);
        if (res.code == 200) {
          message.success(res.message);
        } else {
          return message.error(res.message);
        }
      } catch (e) {
        return message.error(e.message);
      } finally {
        handleOk();
      }
    } else {
      try {
        const res = await addArticle(requestObj);
        if (res.code == 200) {
          message.success(res.message);
        } else {
          return message.error(res.message);
        }
      } catch (e) {
        return message.error(e.message);
      } finally {
        handleOk();
      }
    }
  };

  const handleMdEdit = (value) => {
    console.log("props传递回来", value);
    setContentMd(value);
    form.setFieldValue("contentMd", value);
  };

  const deleteTag = (item) => {
    console.log("id", item);
    setTagsId((pre) => {
      form.setFieldValue(
        "tagsId",
        pre.filter((tag) => tag != item)
      );
      return pre.filter((tag) => tag != item);
    });
  };

  const deteleTypeId = () => {
    setTypeId({});
    form.setFieldValue("typeId", {});
  };

  // 把tagsId和typeId赋值到form的参数中
  const handleTagField = (value) => {
    form.setFieldValue("tagsId", value);
    console.log(form.getFieldValue("tagsId"), "------");
  };
  const handleCateField = (value) => {
    form.setFieldValue("typeId", value);
    console.log(form.getFieldValue("typeId"), "=====");
  };

  // 处理图片上传
  const handleUploadChange = (titleImg) => {
    if (titleImg != "delete") {
      form.setFieldValue("titleImg", titleImg);
      console.log(form.getFieldValue("titleImg"), "form");
      setTitleImg(titleImg);
    } else {
      form.setFieldValue("titleImg", "");
      console.log(form.getFieldValue("titleImg"), "form");
      setTitleImg("");
    }
  };

  const deleteUpload = () => {
    form.setFieldValue("titleImg", "");
    setTitleImg("");
  };

  // 处理自定义校验规则
  const tagsIdValidator = (rules, value, callback) => {
    console.log(value);
    if (value.length <= 0) {
      callback("必需参数");
    } else {
      callback();
    }
  };

  const cateValidator = (rules, value, callback) => {
    let length = Object.keys(value).length;
    console.log(value, length);
    if (length <= 0) {
      callback("必需参数");
    } else {
      callback();
    }
  };
  return (
    <div>
      <Modal
        className={dialogStyle.dialog}
        title={type === 1 ? "编辑文章" : "新增文章"}
        open={isopen}
        onOk={handleOk}
        footer={null}
        onCancel={handleCancel}
        maskClosable={false}
        width="100%"
        style={{ margin: 0, padding: 0, top: 0, maxWidth: "100vw" }}
      >
        <Form
          style={{ padding: "20px" }}
          labelAlign="left"
          onFinishFailed={handleFinishFail}
          onFinish={handleFinish}
          form={form}
        >
          {/* 文章标题以及图片 */}
          <div className={dialogStyle.container}>
            <div className="left">
              <Form.Item label="文章名称" rules={[requireRule]} name="title">
                <Input></Input>
              </Form.Item>
              <Form.Item label="文章简介" rules={[requireRule]} name="summary">
                <Input></Input>
              </Form.Item>
            </div>
            <div className="right">
              <Form.Item label="标题图" name="titleImg">
                <Blupload
                  handleUploadChange={handleUploadChange}
                  titleImg={titleImg}
                ></Blupload>
              </Form.Item>
            </div>
          </div>

          {/* 标签和分类部分 */}
          <div className={dialogStyle.row}>
            <Form.Item
              label="标签"
              rules={[
                {
                  required: true,
                  validator: tagsIdValidator,
                },
              ]}
              name="tagsId"
            >
              {
                <TransitionGroup>
                  {tagsId &&
                    tagsId.length > 0 &&
                    tagsId.map((item) => (
                      <CSSTransition
                        key={item.id}
                        timeout={500}
                        classNames={{
                          enter: dialogStyle["item-enter"],
                          enterActive: dialogStyle["item-enter-active"],
                          exit: dialogStyle["item-exit"],
                          exitActive: dialogStyle["item-exit-active"],
                        }}
                      >
                        <Button className={popverStyle.tagBtn}>
                          {item.tagName}
                          <CloseOutlined
                            className={popverStyle.anticon}
                            onClick={() => deleteTag(item)}
                          />
                        </Button>
                      </CSSTransition>
                    ))}
                </TransitionGroup>
              }
              {
                <CSSTransition
                  in={!tagsId || (tagsId && tagsId.length < 3) ? true : false}
                  timeout={500}
                  classNames={{
                    enter: dialogStyle["item-enter"],
                    enterActive: dialogStyle["item-enter-active"],
                    exit: dialogStyle["item-exit"],
                    exitActive: dialogStyle["item-exit-active"],
                    exitDone: dialogStyle["item-exit-done"],
                  }}
                >
                  <Blpopver
                    list={tagList}
                    type={2}
                    onChange={setTagsId}
                    setField={handleTagField}
                  />
                </CSSTransition>
              }
            </Form.Item>
            <Form.Item
              label="分类"
              rules={[{ required: true, validator: cateValidator }]}
              name="typeId"
            >
              {
                <CSSTransition
                  in={!typeId.id ? true : false}
                  timeout={500}
                  classNames={{
                    enter: dialogStyle["item-enter"],
                    enterActive: dialogStyle["item-enter-active"],
                    exit: dialogStyle["item-exit"],
                    exitActive: dialogStyle["item-exit-active"],
                    exitDone: dialogStyle["item-exit-done"],
                  }}
                >
                  <Blpopver
                    list={cateList}
                    type={1}
                    onChange={setTypeId}
                    setField={handleCateField}
                  />
                </CSSTransition>
              }
              {
                <CSSTransition
                  in={typeId.id ? true : false}
                  timeout={500}
                  classNames={{
                    enter: dialogStyle["item-enter"],
                    enterActive: dialogStyle["item-enter-active"],
                    exit: dialogStyle["item-exit"],
                    exitActive: dialogStyle["item-exit-active"],
                    exitDone: dialogStyle["item-exit-done"],
                  }}
                >
                  <>
                    {typeId.id ? (
                      <Button className={popverStyle.cateBtn}>
                        {typeId.typeName}
                        <CloseOutlined
                          className={popverStyle.anticon}
                          onClick={deteleTypeId}
                        />
                      </Button>
                    ) : null}
                  </>
                </CSSTransition>
              }
            </Form.Item>
          </div>

          {/* 下拉框部分 */}
          <div className={dialogStyle.row}>
            <Form.Item label="是否置顶" rules={[requireRule]} name="isTop">
              <Radio.Group>
                <Radio value={0}>不置顶</Radio>
                <Radio value={1}>置顶</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="状态" rules={[requireRule]} name="status">
              <Radio.Group>
                <Radio value={-1}>下架</Radio>
                <Radio value={0}>待审批</Radio>
                <Radio value={1}>发布</Radio>
                <Radio value={2}>草稿</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="创作类型"
              rules={[requireRule]}
              name="composeType"
            >
              <Radio.Group>
                <Radio value={0}>转载</Radio>
                <Radio value={1}>原创</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="是否推荐"
              rules={[requireRule]}
              name="isRecommend"
            >
              <Radio.Group>
                <Radio value={0}>否</Radio>
                <Radio value={1}>是</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="是否首页轮播"
              rules={[requireRule]}
              name="isBanner"
            >
              <Radio.Group>
                <Radio value={0}>否</Radio>
                <Radio value={1}>是</Radio>
              </Radio.Group>
            </Form.Item>
          </div>
          {/* md编辑组件 */}
          <Form.Item
            rules={[
              {
                required: true,
                message: "必填字段",
                type: "string",
                whitespace: true,
              },
            ]}
            name="contentMd"
            label="内容"
          >
            <BlEditor onChange={handleMdEdit} contentMd={contentMd} />
          </Form.Item>
          <Form.Item style={{ textAlign: "center" }}>
            <Button
              style={{ marginRight: "20px" }}
              size="large"
              onClick={handleCancel}
            >
              取消
            </Button>
            <Button size="large" type="primary" htmlType="submit" loading={loading}>
              确认
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
